import React, { useRef } from 'react';
import cls from 'clsx';
import { LazyloadProps } from './PropsType';
import { useInViewport } from '../hooks';
import { Skeleton } from '../skeleton';
import useNamespace from '../utils/useNamespace';

const Lazyload: React.FC<LazyloadProps> = ({
  height,
  placeholder = <Skeleton title />,
  children,
  className,
  style,
}) => {
  const [bem] = useNamespace('lazyload');
  const ref = useRef<HTMLDivElement | null>(null);
  const inViewPort = useInViewport(ref);

  return inViewPort ? (
    <>{children}</>
  ) : (
    <div ref={ref} className={cls(bem(), className)} style={{ height, ...style }}>
      {placeholder}
    </div>
  );
};

export default Lazyload;
